<template>
  <div>
    <!-- 头部 -->
    <el-row>
      <el-col :span="12">
        <div class="title">案卷信息：</div>
      </el-col>
      <el-col :span="12">
        <div class="my_button">
          <!-- 添加展开按钮，点击时触发 toggleShowAll 函数 -->
          <el-button type="info" size="small" icon="el-icon-sort" @click="toggleShowAll">{{
              showAll ? '收起' : '展开'
            }}
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-edit" @click="editing">编辑</el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 案卷信息表单 -->
    <template v-if="volumeInfo && Object.keys(volumeInfo).length > 0">
      <el-form :label-position="'right'" label-width="160px" :model="volumeList">
        <el-row :gutter="10" style="margin-top: 20px">
          <el-col v-for="comment in visibleCommentList"
                  :key="comment.columnname"
                  :span="12"
                  class="form-col"
                  v-if="comment.columncomment !== ''">
            <el-form-item :label="comment.columncomment + '：'" v-if="comment.columnname !== 'id'">
              <div class="table-content">{{ volumeList[comment.columnname] }}</div>
            </el-form-item>
            <el-form-item :label="comment.columncomment + '：'" v-else>
              <div class="table-content">{{ volumeList[comment.columnname] }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-else>
      <el-empty description="无案卷信息"></el-empty>
    </template>

    <!-- 编辑弹窗 -->
    <el-dialog title="案卷信息编辑：" :visible.sync="dialogVisible" width="50%" center>
      <div class="dialog-content">
        <el-form :model="tempVolumeList">
          <el-row>
            <el-col v-for="comment in volumeCommentList" :key="comment.columnname" :span="12"
                    v-if="comment.columncomment !== ''">
              <el-form-item :label="comment.columncomment + '：'">
                <el-input class="custom-input" v-model="tempVolumeList[comment.columnname]"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogData">恢复</el-button>
        <el-button type="primary" @click="saveDialogData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getVolumeCommentInfo, updateVolumeinfo} from "@/api/system/volumeinfo";
import {listTreemain} from "@/api/system/treemain";

export default {
  props: {
    volumeInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      volumeList: {},
      showAll: false, // 是否显示全部案卷信息
      visibleCommentList: {}, // 可见的案卷字段
      tempVolumeList: {}, // 编辑弹窗中临时保存的数据
      volumeCommentList: null,
      isEditing: false, // 是否处于编辑状态
      dialogVisible: false, // 编辑弹窗是否可见
      // 指定属性非折叠可见
      volume: ['id', 'regprojid', 'vname', 'carrietype', 'amount', 'spec', 'buildorganization', 'savetime',
        'securitylayer', 'filestart', 'fileend', 'injectionperson', 'checkperson', 'injectiondate', 'checkdate',
        'storeposition', 'annotations', 'path', 'topnode'],
      treemainList: [],
    };
  },
  watch: {
    volumeInfo: {
      immediate: true, // 在组件创建时立即执行一次
      handler(newVal) {
        this.volumeList = {...newVal}; // 使用对象的深拷贝方式赋值
        this.tempVolumeList = {...newVal}; // 初始化编辑弹窗中的临时数据
      }
    }
  },
  created() {
    this.getVolumeComment().then(() => {
      this.transferComment()
      this.getList()
    });
  },
  methods: {
    /** 查询档案类别列表 */
    getList() {
      // this.loading = true;
      listTreemain().then(response => {
        this.treemainList = response.data
        // this.treemainList = this.handleTree(response.data, "indexId", "parentId");
        // this.loading = false;
        // console.log(response)
        console.log(this.treemainList)
      });
    },

    //转换可见的属性
    transferComment() {
      // for (const comment of this.volumeCommentList) {
      //   console.log(comment.columnname, "+", comment.columncomment)
      // }

      if (this.showAll) {
        this.visibleCommentList = this.volumeCommentList.filter(comment => comment.columncomment !== '');
      } else {
        const nonEmptyComments = this.volumeCommentList.filter(comment => comment.columncomment !== '');
        this.visibleCommentList = [];
        // 遍历所有字段注释
        for (const comment of nonEmptyComments) {
          // 检查字段是否在eng列表中
          if (this.volume.includes(comment.columnname)) {
            // 如果在，添加到已显示的字段列表
            this.visibleCommentList.push(comment);
          }
        }

        // // 打印volume中有而visibleCommentList的columnname没有的
        // const missingColumns = this.volume.filter(column => {
        //   return !this.visibleCommentList.some(comment => comment.columnname === column);
        // });
        //
        // console.log('在volume中存在但在visibleCommentList中不存在的columnname:', missingColumns);

        // for (let i = 0; i < 10; i++) {
        //   if (nonEmptyComments[i]) {
        //     this.visibleCommentList.push(nonEmptyComments[i]);
        //   } else {
        //     this.visibleCommentList.push({});
        //   }
        // }
      }
    },
    // 切换展开按钮的状态，显示全部案卷信息或部分案卷信息
    toggleShowAll() {
      this.showAll = !this.showAll;
      this.transferComment();
    },
    // 下划线转驼峰命名
    underscoreToCamel(str) {
      return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
    },
    //获取案卷字段信息和注释
    getVolumeComment() {
      return getVolumeCommentInfo()
        .then(res => {
          // this.volumeCommentList = res;
          this.volumeCommentList = res.map(comment => ({
            columncomment: comment.columncomment,
            columnname: this.underscoreToCamel(comment.columnname), // 转换属性名
          }));
        })
        .catch(error => {
          this.$message.error('获取案卷信息注释失败：' + error);
        });
    },
    editing() {
      this.isEditing = true;
      this.dialogVisible = true;
    },
    resetDialogData() {
      this.tempVolumeList = {...this.volumeList};
    },
    saveDialogData() {
      this.$confirm('确认修改吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.isEditing = false;
        // 调用 updateVolumeinfo 方法，并传入 tempVolumeList 数据
        updateVolumeinfo(this.tempVolumeList)
          .then(() => {
            this.$message.success('保存成功！');
            // 如果保存成功，将 tempVolumeList 的数据同步到 volumeList
            this.$emit('updateVolumeInfo');
            this.volumeList = {...this.tempVolumeList};
            this.dialogVisible = false;
          })
          .catch(error => {
            this.$message.error('保存失败：' + error);
            this.dialogVisible = false;
          });
      }).catch(() => {
        // 取消保存
        this.$message.info('已取消保存');
      });
    },
  }
};
</script>

<style>
.title {
  margin-left: 2%;
  margin-top: 10px;
  font-size: 20px;
  font-weight: bold;
  color: rgb(26, 115, 198);
}

.dialog-content {
  max-height: 500px; /* 设置最大高度，内容区域超出时会出现滚动条 */
  overflow-y: auto; /* 内容区域出现滚动条 */
}

.dialog-footer {
  position: sticky;
  bottom: 0;
  padding: 10px;
}

.custom-input {
  width: 98%; /* 设置输入框的宽度，根据实际情况调整 */
}

.my_button {
  display: flex;
  align-items: center;
  margin-right: 2%;
  margin-top: 12px;
}
</style>

